package mysql_sync

import (
	"fmt"
	"gc-rds-ha/internal/common"
	"gc-rds-ha/internal/dao"
	"strings"

	log "github.com/sirupsen/logrus"
	"golang.org/x/net/context"
	"gorm.io/gorm"
)

type MySQLClusterTopologyHistory struct {
	dao.DefaultField

	ClusterAlias string `gorm:"type:varchar(255);not null;default:'';index:idx_alias_host;comment:集群别名"`
	Role         string `gorm:"type:varchar(255);not null;default:'';comment:节点角色"`
	Host         string `gorm:"type:varchar(255);not null;default:'';index:idx_alias_host;comment:节点IP"`
	Port         uint32 `gorm:"not null;default:0;comment:节点端口号"`
	MgrIsEnable  bool   `gorm:"type:tinyint(1);not null;default:0;comment:是否启用MGR复制 0否 1是"`
	MgrRole      string `gorm:"type:varchar(255);not null;default:'';comment:MGR权限"`
	SyncNum      int    `gorm:"not null;default:0;comment:节点历史更新次数:topology.sync_num-1"`

	Tx *gorm.DB `gorm:"-"`
}

var (
	tableCountMySQLClusterTopologyHistory uint32 = 1 //分表数量
)

func init() {

}
func BatchCreateHistoryForSql(batchs []*MySQLClusterTopologyHistory, tx *gorm.DB) error {
	var (
		t            = common.GetDateTimeInfo("format")
		placeHolders []interface{}
		values       []string
		d            MySQLClusterTopologyHistory
	)
	if tx == nil {
		tx = dao.DB
	}
	for _, batch := range batchs {
		values = append(values, "(?, ?, ?, ?, ?, ?, ?, ?, ?)")
		placeHolders = append(placeHolders,
			0, batch.ClusterAlias, batch.Role,
			batch.Host, batch.Port, batch.SyncNum, t, batch.MgrRole, batch.MgrIsEnable,
		)
	}
	sql := fmt.Sprintf("insert into %s (`id`, `cluster_alias`, `role`, `host`, `port`, `sync_num`, `created_at`, `mgr_role`, `mgr_is_enable`) values %s",
		d.TableName(),
		strings.Join(values, ", "),
	)
	if err := tx.Exec(sql, placeHolders...).Error; err != nil {
		log.WithFields(log.Fields{
			"sql": sql,
			"err": err,
		}).Error("BatchCreateHistoryForSql error")
		return err
	}
	return nil
}

func CreateTableMySQLClusterTopologyHistory() {
	d := &MySQLClusterTopologyHistory{}
	for i := uint32(0); i < d.TableCount(); i++ {
		if err := dao.DB.Set("gorm:table_options", "ENGINE=InnoDB").AutoMigrate(d); err != nil {
			log.WithField("", log.Fields{"err": err, "tableName": d.TableName()}).Error("DB AutoMigrate Failed")
		}
	}
}

// TableCount 分表数量
func (d *MySQLClusterTopologyHistory) TableCount() uint32 {
	return tableCountMySQLClusterTopologyHistory
}

// TableName 表名
func (d *MySQLClusterTopologyHistory) TableName() string {
	name := "mysql_cluster_topology_history"
	return name
}

// Model 模型
func (d *MySQLClusterTopologyHistory) Model() *gorm.DB {
	db := dao.DB
	if d.Tx != nil {
		db = d.Tx
	}

	return db.Table(d.TableName()).Model(d)
}

// Create 创建
func (d *MySQLClusterTopologyHistory) Create(ctx context.Context) error {
	m := d.Model()

	if err := m.Create(d).Error; err != nil {
		log.WithFields(log.Fields{"err": err, "d": d}).Error("m.Create(d) error")
	}

	return nil
}

// Get 获取
func (d *MySQLClusterTopologyHistory) Get(ctx context.Context) error {
	m := d.Model()

	if d.ID != 0 {
		m = m.Where("id = ?", d.ID)
	}

	if err := m.Order("id asc").First(d); err != nil {
		log.WithFields(log.Fields{"err": err, "d": d}).Error("m.Create(d) error")
	}
	return nil
}
